package models

import (
	"errors"
	. "lib"
	"log"
	"time"

	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
)

//用户表
type Xuser struct {
	T_id            int64     `orm:"column(t_id);pk"`
	T_username      string    `orm:"unique;size(32)" form:"T_username"  valid:"Required;MaxSize(20);MinSize(6)"`
	T_password      string    `orm:"size(32)" form:"T_password" valid:"Required;MaxSize(20);MinSize(6)"`
	T_repassword    string    `orm:"-" form:"T_repassword" valid:"Required"`
	T_telephone     string    `orm:"unique;size(11)" form:"T_telephone" valid:"Required;MaxSize(11);MinSize(11)"`
	T_email         string    `orm:"size(32)" form:"T_email" valid:"Email"`
	T_remark        string    `orm:"null;size(200)" form:"T_remark" valid:"MaxSize(200)"`
	T_status        int       `orm:"default(2)" form:"T_status" valid:"Range(1,2)"`
	T_lastlogintime time.Time `orm:"null;type(datetime)" form:"-"`
	T_createtime    time.Time `orm:"type(datetime);auto_now_add" `
}

//验证用户信息
func checkUser(u *Xuser) (err error) {
	valid := validation.Validation{}
	b, _ := valid.Valid(&u)
	if !b {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			return errors.New(err.Message)
		}
	}
	return nil
}

func init() {
	orm.RegisterModel(new(Xuser))
}

/************************************************************/

//get user list
func Getuserlist(page int64, page_size int64, sort string) (users []orm.Params, count int64) {
	o := orm.NewOrm()
	user := new(Xuser)
	qs := o.QueryTable(user)
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * page_size
	}
	qs.Limit(page_size, offset).OrderBy(sort).Values(&users)
	count, _ = qs.Count()
	return users, count
}

//添加用户
func AddUser(u *Xuser) (int64, error) {
	if err := checkUser(u); err != nil {
		return 0, err
	}
	o := orm.NewOrm()
	user := new(Xuser)
	user.T_username = u.T_username
	user.T_password = Strtomd5(u.T_password)
	user.T_telephone = u.T_telephone
	user.T_email = u.T_email
	user.T_remark = u.T_remark
	user.T_status = u.T_status

	id, err := o.Insert(user)
	return id, err
}

//更新用户
func UpdateUser(u *Xuser) (int64, error) {
	if err := checkUser(u); err != nil {
		return 0, err
	}
	o := orm.NewOrm()
	user := make(orm.Params)
	if len(u.T_username) > 0 {
		user["T_username"] = u.T_username
	}
	if len(u.T_telephone) > 0 {
		user["T_telephone"] = u.T_telephone
	}
	if len(u.T_email) > 0 {
		user["T_email"] = u.T_email
	}
	if len(u.T_remark) > 0 {
		user["T_remark"] = u.T_remark
	}
	if len(u.T_password) > 0 {
		user["T_password"] = Strtomd5(u.T_password)
	}
	if u.T_status != 0 {
		user["T_status"] = u.T_status
	}
	if len(user) == 0 {
		return 0, errors.New("update field is empty")
	}
	var table Xuser
	num, err := o.QueryTable(table).Filter("T_id", u.T_id).Update(user)
	return num, err
}

func DelUserById(Id int64) (int64, error) {
	o := orm.NewOrm()
	status, err := o.Delete(&Xuser{T_id: Id})
	return status, err
}

func GetUserByUsername(username string) (user Xuser, err error) {
	//user = User{Username: username}
	o := orm.NewOrm()
	usert := new(Xuser)
	err = o.QueryTable(usert).Filter("T_username", username).Filter("T_status", 2).One(&user)
	if err != nil {
		return user, err
	}
	//err = o.Raw("select * from user where status = '2' AND username = ?", username).QueryRow(&user)
	//if err != nil {
	//	return user, err
	//}
	//o.Read(&user, "Username")

	return user, nil
}

func GetUserById(id int64) (user Xuser) {
	user = Xuser{T_id: id}
	o := orm.NewOrm()
	o.Read(&user, "T_id")
	return user
}
